package cn.imvc.app.models;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Goods;
import cn.imvc.app.entities.GoodsSku;
import cn.imvc.app.entities.InventoryFlow;
import cn.imvc.app.entities.Notice;
import cn.imvc.app.repositories.GoodsRepository;
import cn.imvc.app.repositories.GoodsSkuRepository;
import cn.imvc.core.ICache;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;

@Service
public class GoodsSkuModelImpl implements GoodsSkuModel {
	
	@Autowired
	GoodsSkuRepository goodsSkuRepository;
	@Autowired
	GoodsModel goodsModel;
	@Autowired
	GoodsPriceModel goodsPriceModel;
	@Autowired
	InventoryFlowModel inventoryFlowModel;
	@Autowired
	ICache cache;
	@Autowired
	RefRelationModel refRelationModel;
	@Autowired
	UserModel userModel;

	public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestMap() {
		// TODO Auto-generated method stub
		return null;
	}

	public Page<GoodsSku> find(ViewRequest viewRequest) {
		return goodsSkuRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}

	public GoodsSku get(int id) {
		return goodsSkuRepository.findOne(id);
	}

	public GoodsSku save(GoodsSku goodsSku) {
		Goods goods = goodsModel.get(goodsSku.getGoods().getId());
		List<GoodsSku> goodsSkus = goodsSkuRepository.findBySpecNameAndSpecIdAndGoods(goodsSku.getSpecName(), goodsSku.getSpecId(),goods);
		if(goodsSkus == null || goodsSkus.isEmpty()){
//			Goods goods = goodsModel.get(goodsSku.getGoods().getId());
			goodsSku.setGoods(goods);
			GoodsSku goodsSkuTmp = goodsSkuRepository.saveAndFlush(goodsSku);
//			boolean isReview = goodsSku.getState() == (byte)1;
			goodsModel.updateProperties(goods, false);
			cache.removeSecond("MAX_ID", "goodsSku");
			return goodsSkuTmp;
		}else{
			return null;
		}
	}

	public GoodsSku update(GoodsSku goodsSku) {
		GoodsSku goodsSkuTmp = get(goodsSku.getId());
		boolean isCanchange = false;
		if(goodsSku.getSpecId().equals(goodsSkuTmp.getSpecId()) ){
			isCanchange = true;
		}else{
			Goods goods = goodsModel.get(goodsSku.getGoods().getId());
			List<GoodsSku> goodsSkus = goodsSkuRepository.findBySpecNameAndSpecIdAndGoods(goodsSku.getSpecName(), goodsSku.getSpecId(),goods);
			if(goodsSkus == null || goodsSkus.isEmpty()){
				isCanchange = true;
			}
		}
		if(isCanchange){
			Goods goods = goodsModel.get(goodsSku.getGoods().getId());
//			boolean isReview = goodsSku.getState() == (byte)1;
			goodsSku.setGoods(goods);
			goodsSku.setClick(goodsSkuTmp.getClick());
			goodsSku.setCollect(goodsSkuTmp.getCollect());
			goodsSku.setSalenum(goodsSkuTmp.getSalenum());
			goodsSku = goodsSkuRepository.saveAndFlush(goodsSku);
			goodsModel.updateProperties(goods, false);
			String key = "skuId" + goodsSku.getId();
			cache.remove("DATA", key);
			return goodsSku;
		}else{
			return null;
		}
	}

	public String delete(int id) {
		String result = refRelationModel.deleteDateCheck("Goods_Sku", "id", id);
		if(result.equals("")){
			GoodsSku goodsSku = get(id);
			goodsPriceModel.deleteByGoodsSku(goodsSku);
			goodsSkuRepository.delete(id);
			goodsModel.updateProperties(goodsSku.getGoods(), false);
			String key = "skuId" + id;
			cache.remove("DATA", key);
			return "";
		}else{
			return result;
		}
		
	}

	public String deleteBatch(int[] ids) {
		for (int id : ids) {
			String result = delete(id);
			if(!result.equals("")){
				return result;
			}
		}
		return "";
	}

	public List<GoodsSku> findByGoods(Goods goods) {
		return goodsSkuRepository.findByGoods(goods);
	}

	public void deleteByGoods(Goods goods) {
		goodsSkuRepository.deleteByGoods(goods);
	}

	public void updateInventory(InventoryFlow inventoryFlow) {
		GoodsSku goodsSku = get(inventoryFlow.getGoodsSku().getId());
		goodsSku.setInventory(goodsSku.getInventory()+inventoryFlow.getCount());
		goodsSkuRepository.saveAndFlush(goodsSku);
		inventoryFlow.setUserId(userModel.getSessionUser().getId());
		inventoryFlow.setDirection((byte)(inventoryFlow.getCount() > 0 ? 0:1));
		inventoryFlow.setAfterChange(goodsSku.getInventory());
		inventoryFlowModel.save(inventoryFlow);
	}

	public int getSkuBySpec(String specId,int goodsid) {
		specId = specId.equals("") ? specId : (specId+":");
		String specIdStr = "%"+specId+"%";
		return goodsSkuRepository.getGoodsSkuBySpecId(specIdStr,goodsid);
	}
	
	public int getSkuBySpecNoMothBall(String specId,int goodsid) {
		specId = specId.equals("") ? specId : (specId+":");
		String specIdStr = "%"+specId+"%";
		return goodsSkuRepository.getGoodsSkuBySpecIdNoMothBall(specIdStr,goodsid);
	}

	/**
	 * 封存商品所有的sku
	 */
	public void updateMothballAll(int goodsId){
		Goods goods = goodsModel.get(goodsId);
		List<GoodsSku> goodsSkus = goodsSkuRepository.findByGoods(goods);
		Iterator<GoodsSku> iterator = goodsSkus.iterator();
		while (iterator.hasNext()) {
			GoodsSku goodsSku = (GoodsSku) iterator.next();
			//设为封存状态
			goodsSku.setState((byte)2);
			goodsSkuRepository.saveAndFlush(goodsSku);
		}
	}

	/**
	 * 根据goods的状态，同步sku的状态
	 */
	public void updateSkuState(Goods goods) {
		goods = goodsModel.get(goods.getId());
		List<GoodsSku> goodsSkus = goodsSkuRepository.findByGoods(goods);
		Iterator<GoodsSku> iterator = goodsSkus.iterator();
		while (iterator.hasNext()) {
			GoodsSku goodsSku = (GoodsSku) iterator.next();
			//同步时过滤已下架状态
			if(goodsSku.getState() != 0 || goods.getState() == 0){
				goodsSku.setState((byte)goods.getState());
				goodsSkuRepository.saveAndFlush(goodsSku);
			}
		}
	}
}
